<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间格式化</title>
</head>
<body>
   <h1 class="time">00:00:00</h1>
    <script>
    let timeEl = document.querySelector("h1");
    //时间格式化
    JsonInfo = {
        name:"phone",
        price:"1234",
        time:1659252290626
    }

    //将时间转化为特定的格式
    function formatDate(time,formatString)
    {
         //创建时间对象
         let date = new Date(time);
         //获取时间对象的时分秒等
         let obj = {
            "Y+":date.getFullYear(),
            "M+":date.getMonth(),
            "d+":date.getDate(),
            "h+":date.getHours(),
            "m+":date.getMinutes(),
            "s+":date.getSeconds(),
         }

         //遍历填入到formatString中
         for(key in obj)
         {
           
            //检查是否符合格式要求
            if(new RegExp(key).test(formatString))
            {
                //得到一个结果并且格式化
                const value = (obj[key]+"").padStart(2,"0");
                console.log(value);
                formatString =  formatString.replace(new RegExp(key),value);
            }
         }

         return formatString;
    }
    

    timeEl.textContent = formatDate(JsonInfo.time,"YYYY-MM-dd hh:mm:ss");
    
   
     
    </script>
</body>
</html>